#include <iostream>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <cstring>
#include <unistd.h>

#include "Comm.hpp"
#define Retry_count 5

void Usage(const std::string &proc)
{
    std::cout << "Usage\n\t" << proc << " serverip serverport" << std::endl;
}

bool visitServer(std::string serverip, uint16_t serverport, int *cnt)
{
    std::string inbuffer;
    char server_list[1024];
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (socket < 0)
    {
        std::cerr << "socket error" << std::endl;
        return false;
    }

    bool ret = true;
    ssize_t n = 0;
    ssize_t m = 0;
    // 发起连接
    struct sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    // server.sin_addr.s_addr = inet_addr(serverip.c_str());
    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);
    n = connect(sockfd, CONV(&server), sizeof server);
    if (n < 0)
    {
        std::cerr << "connect error" << std::endl;
        ret = false;
        goto END;
    }

    // 连接成功！！
    *cnt = 0;

    n = read(sockfd, server_list, sizeof(server_list) - 1);
    if (n > 0)
    {
        server_list[n] = 0;
        std::cout << "服务器提供的服务列表是: " << server_list << std::endl;
    }
    std::cout << "Please selece server: ";
    getline(std::cin, inbuffer);
    write(sockfd, inbuffer.c_str(), inbuffer.size());

    std::cout << "Entry> ";
    getline(std::cin, inbuffer);
    if (inbuffer == "quit")
        goto END;

    n = write(sockfd, inbuffer.c_str(), inbuffer.size());
    if (n > 0)
    {
        char buffer[1024];
        m = read(sockfd, buffer, sizeof(buffer) - 1);
        if (m > 0)
        {
            buffer[m] = 0;
            std::cout << buffer << std::endl;
        }
        else
        {
            ret = false;
            goto END;
        }
    }
    else
    {
        ret = false;
        goto END;
    }

END:
    close(sockfd);
    return ret;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    int cnt = 0;
    while (cnt < Retry_count)
    {
        bool ret = visitServer(serverip, serverport, &cnt);
        if (ret)
            break;
        else
        {
            std::cout << "server offline, retrying..., cnt: " << cnt++ << std::endl;
            sleep(1);
        }
    }
    if (cnt >= Retry_count)
    {
        std::cout << "server offline!!!" << std::endl;
    }
    return 0;
}